<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="分类编号" prop="id">
            <el-input v-model="formData.id" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="formData.categoryName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="排序序号" prop="sortOrder">
            <el-input v-model="formData.sortOrder" placeholder="请输入" />
          </el-form-item>
        </el-col>

      </el-row>

    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Advance ref="preFormRef" :items="formData.items" :disabled="disabled" />
  <FeeDetail ref="feeDetailRef" :items="formData.items" :disabled="disabled" />
</template>
<script setup lang="ts">
  import { getIntDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { StockInApi, StockInVO } from '@/api/erp/stock/in'
import Advance from './components/Advance.vue'
import FeeDetail from './components/FeeDetail.vue'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import StockList from './components/StockList.vue'
import { ElMessage } from 'element-plus'
/** ERP 其它入库单 表单 */
defineOptions({ name: 'StockInForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  name: undefined,
  materialCategoryId: undefined,
  materialSource: undefined,
  specification: undefined,
  model: undefined,
  category: undefined,
  color: undefined,
  materialGrade: undefined,
  barcode: undefined,
  attachment: undefined,
  productionDate: undefined,
  brand: undefined,
  weight: undefined,
  drawingNumber: undefined,
  materialQuality: undefined,
  characteristics: undefined,
  thread: undefined,
  oem1: undefined,
  oem2: undefined,
  oem3: undefined,
  test001: undefined,
  customerModel: undefined,
  version: undefined,
  purchaserId: undefined,
  warehouseLocationId: undefined,
  warehouseAreaId: undefined,
  remarks:undefined
})
const formRules = reactive({
  name: [{ required: true, message: '物料名称不能为空', trigger: 'blur' }],
  materialCategoryId: [{ required: true, message: '物料分类不能为空', trigger: 'blur' }],
  materialSource: [{ required: true, message: '物料来源不能为空', trigger: 'blur' }],
  specification: [{ required: true, message: '规格不能为空', trigger: 'blur' }],
  model: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '类别不能为空', trigger: 'blur' }],
  color: [{ required: true, message: '颜色不能为空', trigger: 'blur' }],
  materialGrade: [{ required: true, message: '物料等级不能为空', trigger: 'blur' }],
  version: [{ required: true, message: '版本不能为空', trigger: 'blur' }],
  purchaserId: [{ required: true, message: '采购员不能为空', trigger: 'blur' }],
  warehouseLocationId: [{ required: true, message: '库位不能为空', trigger: 'blur' }],
  warehouseAreaId: [{ required: true, message: '仓库区域不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const feeDetailRef = ref()
const feeDetailForm = () => {
  feeDetailRef.value.open()
}
const preFormRef = ref()

const preOrder = () => {
  preFormRef.value.open()
}
const allocation = () => {
  ElMessage({
    message: '分摊成功',
    type: 'success',
    plain: true
  })
}
/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StockInApi.getStockIn(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载供应商列表
  supplierList.value = await SupplierApi.getSupplierSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  console.log(formData.value)
  // await formRules.value.validate()
  // await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StockInVO
    if (formType.value === 'create') {
      await StockInApi.createMaterialCategory(data)
      message.success(t('common.createSuccess'))
    } else {
      await StockInApi.updateMaterialCategory(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    supplierId: undefined,
    settlementDate: undefined,
    remark: undefined,
    items: [],
    entryOrderNumber: undefined,
    relatedPurchaseOrder: undefined,
    settlementPeriod: undefined,
    project: undefined,
    projectPhase: undefined,
    documentDate: undefined,
    createdBy: undefined,
    department: undefined,
    operator: undefined,
    deliveryOrderNumber: undefined,
    purchaseRemark: undefined,
    amountExcludingTax: undefined,
    amountIncludingTax: undefined,
    customerOrderNumber: undefined,
    discountAmount: undefined,
    discountRate: undefined,
    transactionAmount: undefined,
    invoiceType: undefined,
    taxRate: undefined,
    paymentMethod: undefined,
    deductAdvancePayment: undefined,
    purchaseFee: undefined
  }
  formRef.value?.resetFields()
}
</script>
